<?
/**
 * Project:	Smarty-Light, a smarter template engine
 * File:	class.template.php
 * Author:	Paul Lockaby <paul@paullockaby.com>
 * Version:	2.1.0
 * Copyright:	2003,2004 by Paul Lockaby
 * Credit:	This work is a light version of Smarty: the PHP compiling
 *		template engine, v2.5.0-CVS. Smarty was originally
 *		programmed by Monte Ohrt and Andrei Zmievski and can be
 *		found at http://smarty.php.net
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 * You may contact the author of Smarty-Light by e-mail at:
 * paul@paullockaby.com
 *
 * The latest version of Smarty-Light can be obtained from:
 * http://www.paullockaby.com/projects/smarty-light
 *
 */

class SmartyLight {
	// public configuration variables
	var $left_tag			= "<{";		// the left delimiter for template tags
	var $right_tag			= "}>";		// the right delimiter for template tags
	var $cache			= false;	// whether or not to allow caching of files
	var $force_compile		= false;	// force a compile regardless of saved state
	var $template_dir		= "templates";	// where the templates are to be found
	var $plugin_dir			= "plugins";	// where the plugins are to be found
	var $compile_dir		= "compiled";	// the directory to store the compiled files in
	var $config_dir			= "templates";	// where the config files are
	var $cache_dir			= "cached";	// where cache files are stored
	var $config_overwrite		= false;
	var $config_booleanize		= true;
	var $config_fix_new_lines	= true;
	var $config_read_hidden		= true;
	var $cache_lifetime		= 0;		// how long the file in cache should be considered "fresh"

	// private internal variables
	var $_vars		= array();	// stores all internal assigned variables
	var $_confs		= array();	// stores all internal config variables
	var $_plugins		= array();	// stores all internal plugins
	var $_linenum		= 0;		// the current line number in the file we are processing
	var $_file		= "";		// the current file we are processing
	var $_config_obj	= null;
	var $_compile_obj	= null;
	var $_compile_id	= null;	
	var $_compile_dir	= "";		// stores where this specific file is going to be compiled
	var $_cache_id		= null;
	var $_cache_dir		= "";		// stores where this specific file is going to be cached
	var $_sl_md5		= '39fc70570b8b60cbc1b85839bf242aff';

	function assign($key, $value = null) {
		if (is_array($key)) {
			foreach($key as $var => $val)
				if ($var != "" && !is_numeric($var))
					$this->_vars[$var] = $val;
		} else {
			if ($key != "" && !is_numeric($key))
				$this->_vars[$key] = $value;
		}
	}

	function assign_config($key, $value = null) {
		if (is_array($key)) {
			foreach($key as $var => $val)
				if ($var != "" && !is_numeric($var))
					$this->_confs[$var] = $val;
		} else {
			if ($key != "" && !is_numeric($key))
				$this->_confs[$key] = $value;
		}
	}

	function clear($key = null) {
		if ($key == null) {
			$this->_vars = array();
		} else {
			if (is_array($key)) {
				foreach($id as $index => $value)
					if (in_array($value, $this->_vars))
						unset($this->_vars[$index]);
			} else {
				if (in_array($key, $this->_vars))
					unset($this->_vars[$key]); // Fixed a bug where it wouldnt clear the variable [VARUN]
			}
		}
	}

	function clear_config($key = null) {
		if ($key == null) {
			$this->_conf = array();
		} else {
			if (is_array($key)) {
				foreach($key as $index => $value)
					if (in_array($value, $this->_conf))
						unset($this->_conf[$index]);
			} else {
				if (in_array($key, $this->_conf))
					unset($this->_conf[$key]);
			}
		}
	}

	function &get_vars($key = null) {
		if ($key == null) {
			return $this->_vars;
		} else {
			if (isset($this->_vars[$key]))
				return $this->_vars[$key];
			else
				return null;
		}
	}

	function &get_config_vars($key = null) {
		if ($key == null) {
			return $this->_confs;
		} else {
			if (isset($this->_confs[$key]))
				return $this->_confs[$key];
			else
				return null;
		}
	}
	
	function clear_compiled($file = null, $compile_id = null) {
		$this->_destroy_dir($file, $compile_id, $this->_get_dir($this->compile_dir));
	}

	function clear_cached($file = null, $cache_id = null) {
		if (!$this->cache)
			return;
		$this->_destroy_dir($file, $cache_id, $this->_get_dir($this->cache_dir));
	}

	function is_cached($file, $cache_id = null) {
		if (!$this->cache)
			return false;
		$name = md5($file).'.php';
		$this->_cache_dir = $this->_get_dir($this->_cache_dir);
		if (file_exists($this->_cache_dir.$name) && (((time() - filemtime($this->_cache_dir.$name)) < $this->cache_lifetime) || $this->cache_lifetime == -1) && (filemtime($this->_cache_dir.$name) > filemtime($this->template_dir.$file)))
			return true;
		else
			return false;
	}

	function register_modifier($modifier, $implementation) {
		$this->_plugins["modifier"][$modifier] = $implementation;
	}

	function unregister_modifier($modifier) {
		if (isset($this->_plugins["modifier"][$modifier]))
			unset($this->_plugins["modifier"][$modifier]);
	}

	function register_function($function, $implementation) {
		$this->_plugins["function"][$function] = $implementation;
	}

	function unregister_function($function) {
		if (isset($this->_plugins["function"][$function]))
			unset($this->_plugins["function"][$function]);
	}

	function register_compiler($function, $implementation) {
		$this->_plugins["compiler"][$function] = $implementation;
	}

	function unregister_compiler($function) {
		if (isset($this->_plugins["compiler"][$function]))
			unset($this->_plugins["compiler"][$function]);
	}

	function register_block($function, $implementation) {
		$this->_plugins["block"][$function] = $implementation;
	}

	function unregister_block($function) {
		if (isset($this->_plugins["block"][$function]))
			unset($this->_plugins["block"][$function]);
	}

	function template_exists($file) {
		if (file_exists($this->_get_dir($this->template_dir).$file))
			return true;
		else
			return false;
	}

	function display($file, $compile_id = null, $cache_id = null) {
		$this->fetch($file, $compile_id, $cache_id, true);
	}

	function fetch($file, $compile_id = null, $cache_id = null, $display = false) {
		$name = md5($file).'.php';
		$this->_compile_id = $compile_id;
		$this->_cache_id = $cache_id;
		$this->template_dir = $this->_get_dir($this->template_dir);
		$this->_compile_dir = $this->_build_dir($this->compile_dir, $this->_compile_id);
		if ($this->cache)
			$this->_cache_dir = $this->_build_dir($this->cache_dir, $this->_cache_id);

		// don't display any errors
		$this->_error_level = error_reporting(E_ALL & ~E_NOTICE);

		if (!$this->force_compile && $this->cache && file_exists($this->_cache_dir.$name) && (((time() - filemtime($this->_cache_dir.$name)) < $this->cache_lifetime) || $this->cache_lifetime == -1) && (filemtime($this->_cache_dir.$name) > filemtime($this->template_dir.$file))) {
			ob_start();
			include($this->_cache_dir.$name);
			$output = ob_get_contents();
			ob_end_clean();
		} else {
			$output = $this->_fetch_compile($file, $compile_id, $cache_id);
			if ($this->cache) {
				$f = fopen($this->_cache_dir.$name, "w");
				fwrite($f, $output);
				fclose($f);
			}
		}

		if (strpos($output, $this->_sl_md5) !== false) {
			preg_match_all('!' . $this->_sl_md5 . '{_run_insert (.*)}' . $this->_sl_md5 . '!U',$output,$_match);
			foreach($_match[1] as $value) {
				$arguments = unserialize($value);
				$output = str_replace($this->_sl_md5 . '{_run_insert ' . $value . '}' . $this->_sl_md5, call_user_func_array('insert_' . $arguments['name'], array((array)$arguments, $this)), $output);
			}
		}

		error_reporting($this->_error_level);
		if ($display)
			echo $output;
		else
			return $output;
	}

	function config_load($file, $section_name = null, $var_name = null) {
		$name = md5($file.$section_name.$var_name).'.php';
		$this->config_dir = $this->_get_dir($this->config_dir);
		$this->compile_dir = $this->_get_dir($this->compile_dir);
		if (!$this->force_compile && file_exists($this->compile_dir.$name) && (filemtime($this->compile_dir.$name) > filemtime($this->config_dir.$file))) {
			include($this->compile_dir.$name);
			return true;
		}

		if (!is_object($this->_config_obj)) {
			require_once("class.config.php");
			$this->_config_obj = new config;
			$this->_config_obj->overwrite = $this->config_overwrite;
			$this->_config_obj->booleanize = $this->config_booleanize;
			$this->_config_obj->fix_new_lines = $this->config_fix_new_lines;
			$this->_config_obj->read_hidden = $this->config_read_hidden;
		}
		if (!($_result = $this->_config_obj->config_load($this->config_dir.$file, $section_name, $var_name))) {
			return false;
		}

		if (!empty($var_name) || !empty($section_name)) {
			$output = "\$this->_confs = " . var_export($_result, true) . ";";
		} else {
			// must shift of the bottom level of the array to get rid of the section labels
			$_temp = array();
			foreach($_result as $value)
				$_temp = array_merge($_temp, $value);
			$output = "\$this->_confs = " . var_export($_temp, true) . ";";
		}

		$f = fopen($this->compile_dir.$name, "w");
		fwrite($f, '<?php ' . $output . ' ?>');
		fclose($f);
		eval($output);
		return true;
	}

	function _fetch_compile($file, $compile_id) {
		$name = md5($file).'.php';

		if (!$this->force_compile && file_exists($this->_compile_dir.$name) && (filemtime($this->_compile_dir.$name) > filemtime($this->template_dir.$file))) {
			ob_start();
			include($this->_compile_dir.$name);
			$output = ob_get_contents();
			ob_end_clean();
			error_reporting($this->_error_level);
			return $output;
		}

		if ($this->template_exists($file)) {
			$f = fopen($this->template_dir.$file, "r");
			$file_contents = fread($f, filesize($this->template_dir.$file));
			$this->_file = $file;
			fclose($f);
		} else {
			$this->trigger_error("file '$file' does not exist", E_USER_ERROR);
		}

		if (!is_object($this->_compile_obj)) {
			require_once("./includes/SmartyLight/class.compiler.php");
			$this->_compile_obj = new compiler;
		}
		$this->_compile_obj->left_tag = $this->left_tag;
		$this->_compile_obj->right_tag = $this->right_tag;
		$this->_compile_obj->plugin_dir = &$this->plugin_dir;
		$this->_compile_obj->template_dir = &$this->template_dir;
		$this->_compile_obj->cache = $this->cache;
		$this->_compile_obj->_compile_id = $this->_compile_id;
		$this->_compile_obj->_vars = &$this->_vars;
		$this->_compile_obj->_confs = &$this->_confs;
		$this->_compile_obj->_plugins = &$this->_plugins;
		$this->_compile_obj->_linenum = &$this->_linenum;
		$this->_compile_obj->_file = &$this->_file;
		$output = $this->_compile_obj->_compile_file($file_contents);

		$f = fopen($this->_compile_dir.$name, "w");
		fwrite($f, $output);
		fclose($f);

		ob_start();
		eval(' ?>' . $output . '<?php ');
		$output = ob_get_contents();
		ob_end_clean();
		error_reporting($this->_error_level);
		return $output;
	}

	function _run_modifier() {
		$arguments = func_get_args();
		list($variable, $modifier, $_map_array) = array_splice($arguments, 0, 3);
		array_unshift($arguments, $variable);
		if ($_map_array && is_array($variable))
			foreach($variable as $key => $value)
				$variable[$key] = call_user_func_array($this->_plugins["modifier"][$modifier], $arguments);
		else
			$variable = call_user_func_array($this->_plugins["modifier"][$modifier], $arguments);
		return $variable;
	}

	function _run_insert($arguments) {
		if ($this->cache) {
			return $this->_sl_md5 . '{_run_insert ' . serialize((array)$arguments) . '}' . $this->_sl_md5;
		} else {
			if (!function_exists('insert_' . $arguments['name']))
				$this->trigger_error("function 'insert_" . $arguments['name'] . "' does not exist in 'insert'", E_USER_ERROR);
			if (isset($arguments['assign']))
				$this->assign($arguments['assign'], call_user_func_array('insert_' . $arguments['name'], array((array)$arguments, $this)));
			else
				return call_user_func_array('insert_' . $arguments['name'], array((array)$arguments, $this));
		}
	}

	function _get_dir($dir) {
		if (empty($dir))
			$dir = '.';
		if (substr($dir, -1) != '/')
			$dir .= DIRECTORY_SEPARATOR;
		return $dir;
	}

	function _build_dir($dir, $id) {
		$_args = explode('|', $id);
		if (count($_args) == 1 && empty($_args[0]))
			return $this->_get_dir($dir);
		umask(0000);
		$_result = $this->_get_dir($dir);
		foreach($_args as $value) {
			$_result .= $value.DIRECTORY_SEPARATOR;
			@mkdir($_result, 0777);
		}
		return $_result;
	}

	function _destroy_dir($file, $id, $dir) {
		if ($file == null && $id == null) {
			if (is_dir($dir))
				if($d = opendir($dir))
					while(($f = readdir($d)) !== false)
						if ($f != '.' && $f != '..')
							$this->_rm_dir($dir.$f.DIRECTORY_SEPARATOR);
		} else {
			if ($id == null) {
				@unlink($dir.md5($file).'.php');
			} else {
				$_args = "";
				foreach(explode('|', $id) as $value)
					$_args .= $value.DIRECTORY_SEPARATOR;
				$this->_rm_dir($dir.DIRECTORY_SEPARATOR.$_args);
			}
		}
	}

	function _rm_dir($dir) {
		if ($d = opendir($dir)) {
			while(($f = readdir($d)) !== false) {
				if ($f != '.' && $f != '..') {
					if (is_dir($dir.$f))
						$this->_rm_dir($dir.$f.DIRECTORY_SEPARATOR);
					if (is_file($dir.$f))
						@unlink($dir.$f);
				}
			}
			@rmdir($dir.$f);
		}
	}

	function trigger_error($error_msg, $error_type = E_USER_ERROR, $file = null, $line = null) {
		if(isset($file) && isset($line))
			$info = ' ('.basename($file).", line $line)";
		else
			$info = null;
		trigger_error('TPL: [in ' . $this->_file . ' line ' . $this->_linenum . "]: syntax error: $error_msg$info", $error_type);
	}
}



//=======================================
//###################################
// Kayako Web Solutions
//
// Source Copyright 2001-2004 Kayako Web Solutions
// Unauthorized reproduction is not allowed
// License Number: $%LICENSE%$
// $Author: vshoor $ ($Date: 2006/09/12 12:45:52 $)
// $RCSfile: class.template.php,v $ : $Revision: 1.14 $ 
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
//###################################
//=======================================



/**
* ###############################################
* CLASS START: Template
* ###############################################
*/

/**
* Wrapper class for Smarty adding db fetching routines and other theme management functions
*/
class Template extends SmartyLight
{
	/**
	* Points to the path where the templates are
	*/
	var $path = "";

	/**
	* Cache storage array
	*/
	var $store = array();

	/**
	* The default group
	*/
	var $groupid = "";


	/**
	* Internationalization variables
	*/
	// var $defaultLanguage = "en-us";
	var $defaultLanguage = "vi-vn";
	var $lang_path    = "./locale/";
    var $activeLanguage;
    var $translation = array();
	var $languagetabletype = "file";

	/**
	* Updates the default group under which templates will be fetched
	*/
	function setGroup($groupid)
	{
		global $_SWIFT;

		$this->groupid = $groupid;

		$languagecode = $_SWIFT["languagecache"][$_SWIFT["tgroupcache"][$groupid]["languageid"]]["languagecode"];
		if (empty($languagecode))
		{
			// $languagecode = "en-us";
			$languagecode = "vi-vn";
		}

		if ($this->activeLanguage != $languagecode)
		{
			$this->activeLanguage = $languagecode;
		}

		return true;
	}

	/**
	* Sets the path where class will look for templates
	*/
	function setPath($newpath)
	{
		$this->path = $newpath;

		return true;
	}

	/*
	* Checks to see whether a template is valid, only templates that end in .tpl will be executed
	*/
	function isValidTemplate($name)
	{
		$data = explode(".", $name);
		if (strtolower($data[count($data)-1]) == "tpl")
		{
			return true;
		} else {
			return false;
		}
	}

	/**
	* Displays the template under the set path
	*/
	function displayTemplate($name, $customtype = "", $silent = false)
	{
		global $_SWIFT;

		if (SWIFT_AREA == SWIFT_CLIENT || SWIFT_AREA == SWIFT_VISITOR || $customtype == TEMPLATE_DB)
		{
			// DB Template
			return $this->customCompiler($name, TEMPLATE_DB, $silent);
		} else {
			if (!$this->isValidTemplate($name))
			{
				return false;
			}

			if (file_exists($this->path.$name))
			{
				$this->template_dir = $this->path;
				return $this->customCompiler($name, TEMPLATE_FILE, $silent);
			}			
		}
	}

	/**
	* Caches the template by fetching them in single query
	*/
	function cacheData($templatelist)
	{
		global $dbCore;

		$result = $dbCore->query("SELECT templates.*, templatedata.*, templategroups.title AS tgrouptitle, templategroups.description AS tgroupdescription, templategroups.companyname FROM `". TABLE_PREFIX ."templates` AS templates LEFT JOIN `". TABLE_PREFIX ."templatedata` AS templatedata ON (templates.templateid = templatedata.templateid) LEFT JOIN `". TABLE_PREFIX ."templategroups` AS templategroups ON(templates.tgroupid = templategroups.tgroupid) WHERE templategroups.tgroupid = '". intval($this->groupid) ."' AND templates.name IN(". buildIN($templatelist) .");", 5);
		while ($dbCore->nextRecord(5))
		{
			$this->store[$this->groupid][$dbCore->Record5["name"]] = $dbCore->Record5;
		}

		if ($result)
		{
			return true;
		} else {
			return false;
		}
	}

	/**
	* Caches the template by fetching them in single query
	*/
	function cache($templatelist)
	{
		global $dbCore;

		$result = $dbCore->query("SELECT * FROM `". TABLE_PREFIX ."templates` WHERE tgroupid = '". intval($this->groupid) ."' AND name IN(". buildIN($templatelist) .");", 5);
		while ($dbCore->nextRecord(5))
		{
			$this->store[$this->groupid][$dbCore->Record5["name"]] = $dbCore->Record5;
		}

		if ($result)
		{
			return true;
		} else {
			return false;
		}
	}

	/**
	* Caches the template by fetching them in single query
	*/
	function cacheTemplate($templatename)
	{
		return $this->cacheData(array($templatename));
	}

	/**
	* Gets the basic template info, doesnt get the actual data
	*/
	function loadTemplateInfo($templatename)
	{
		global $dbCore;

		return $this->cache(array($templatename));
	}

	/**
	* Fetches the template data from db or if it is in store cached earlier, fetches it from data storage
	*/
	function fetchTemplate($templatename)
	{
		global $dbCore;

		if (!$this->templateInCache($templatename))
		{
			$this->loadTemplateInfo($templatename);
		}

		return $this->getTemplateFromCache($templatename);
	}

	/**
	* Returns timestamp for a given template
	*/
	function fetchTimestamp($templatename)
	{
		if (SWIFT_AREA == SWIFT_CLIENT || SWIFT_AREA == SWIFT_VISITOR)
		{
			return $this->store[$this->groupid][$templatename]["dateline"]+date("Z")+60;
		} else {
			return @filemtime($this->template_dir.$templatename);
		}
	}

	/**
	* Returns true or false if a template exists in cache storage
	*/
	function templateInCache($templatename)
	{
		if (isset($this->store[$this->groupid][$templatename]))
		{
			return true;
		} else {
			return false;
		}
	}

	/**
	* Returns template data from cache
	*/
	function getTemplateFromCache($templatename)
	{
		$templatedata = $this->store[$this->groupid][$templatename]["contents"];
		if (empty($templatedata))
		{
			return false;
		} else {
			return $templatedata;
		}
	}


	function getLanguages()
	{
		$matches = $result = array();

		@preg_match_all("/([a-z\-]*)/i", $_SERVER['HTTP_ACCEPT_LANGUAGE'], $matches);
		
		$matches[1][] = $this->defaultLanguage;
		
		for ($ii=0; $ii<count($matches[1]); $ii++)
		{
			if (!empty($matches[1][$ii]))
			{
				$result[] = $matches[1][$ii];
			}
		}
		return $result;
	}

	function loadLanguageTable()
	{
		global $_SWIFT, $datastore;

		if ($this->languagetabletype == "db") {
			// Add the default language section to data store cache loading statement, other sections can be loaded by modules in constructors
			$language = cleanVar($_SWIFT["clientlanguage"]);
			$this->activeLanguage = $language;
			$datastore->cacheLanguage($language, "default");
			foreach ($datastore->languagestorekeys as $key=>$val)
			{
				$datastore->cacheLanguage($language, $val);
			}

			return true;
		} else {
			$language = cleanVar($_SWIFT["adminlanguage"]);
			$filename = $this->lang_path.$language."/".$language.".php";

			if(!file_exists($filename))
			{
				$filename = $this->lang_path.$this->defaultLanguage."/".$this->defaultLanguage.".php";
			}

			@require_once($filename);

			if(is_array($__LANG))
			{
				$this->translation = array();
				$this->translation = array_merge($this->translation, $__LANG);
				$_SWIFT["language"] = &$this->translation;
				$this->activeLanguage = $language;
				@$this->assign("language", $this->translation);
				unset($__LANG);

				return true;
			} 
		}

		return false;
	}

	/*
	* Loads a specific language section file
	*/
	function loadLanguageSection($sectionname, $customtype = "")
	{
		global $_SWIFT, $datastore;

		if (($this->languagetabletype == "db" && empty($customtype)) || ($customtype == TEMPLATE_DB)) {
			// Load the language table from database, we are in client area!
			if (empty($this->activeLanguage))
			{
				$languagecode = $_SWIFT["languagecache"][$_SWIFT["tgroupcache"][$this->groupid]["languageid"]]["languagecode"];
			} else {
				$languagecode = $this->activeLanguage;
			}
			if (empty($languagecode))
			{
				// $languagecode = "en-us";
				$languagecode = "vi-vn";
			}
			if (is_array($sectionname))
			{
				for ($ii=0; $ii<count($sectionname); $ii++)
				{
					if (!in_array($languagecode.":".$sectionname, $datastore->languagecache))
					{
						$datastore->cacheLanguage($languagecode, $sectionname[$ii]);
					}
				}
			} else {
				if (!in_array($languagecode.":".$sectionname, $datastore->languagecache))
				{
					$datastore->cacheLanguage($languagecode, $sectionname);
				}
			}

			$datastore->loadData(true);

			return true;
		} else {
			$language = cleanVar($_SWIFT["adminlanguage"]);
			$sectionname = cleanVar($sectionname);

			$filename = $this->lang_path.$language."/".$sectionname.".php";

			if(!file_exists($filename))
			{
				$filename = $this->lang_path.$this->defaultLanguage."/".$sectionname.".php";
				if (!file_exists($filename))
				{
					return false;
				}
			}

			require_once($filename);

			if(is_array($__LANG))
			{
				$this->translation = array_merge($this->translation, $__LANG);
				@$this->assign("language", $this->translation);
				unset($__LANG);

				return true;  
			} 
		}

		return false;
	}

	/*
	* Determines template type according to SWIFT_AREA
	*/
	function determineType()
	{
		if (SWIFT_AREA == SWIFT_CLIENT || SWIFT_AREA == SWIFT_VISITOR)
		{
			// We only use db templates in Client Area
			return TEMPLATE_DB;
		} else {
			return TEMPLATE_FILE;
		}
	}

	/*
	* Custom Template Compiler function
	*/
	function customCompiler($templatename, $templatetype, $silent = false)
	{
		global $_SWIFT;

		if ($templatetype == TEMPLATE_DB)
		{
			// We salt the template name with type and group as user is in client area
			$name = md5($templatetype. ":". $this->groupid .":".$templatename).'.php';
			$this->fetchTemplate($templatename);
		} else {
			// We salt the template name with type and theme as user is in admin/staff area
			$name = md5($templatetype. ":". $_SWIFT["theme"] .":".$templatename).'.php';
		}

		if (($templatetype == TEMPLATE_DB) && (@filemtime("./cache/".$name) < $this->fetchTimestamp($templatename)))
		{
			// We wont fetch a precompiled version if time since change in db is more than the filemtime, we will instead compile it again.
			$nofetch = true;
		}

		if (($templatetype == TEMPLATE_FILE) && (@filemtime("./cache/".$name) < $this->fetchTimestamp($templatename)))
		{
			// We wont fetch a precompiled version if time since change in db is more than the filemtime, we will instead compile it again.
			$nofetch = true;
		}

		if (!$this->force_compile && file_exists("./cache/".$name) && $nofetch != true) {
			ob_start();
			include("./cache/".$name);
			$output = ob_get_contents();
			ob_end_clean();
			error_reporting($this->_error_level);
			return $output;
		}

		if ($templatetype == TEMPLATE_FILE)
		{
			if ($this->template_exists($templatename)) {
				// VARUN: Fix for fread bug
//				$f = fopen($this->template_dir.$templatename, "r");
				$this->_file = $templatename;
//				fclose($f);
				$file_contents = implode("", file($this->template_dir.$templatename));
			} else {
				$this->trigger_error("file '$file' does not exist", E_USER_ERROR);
			}			
		} else if ($templatetype == TEMPLATE_DB) {
			if (!$this->cacheTemplate($templatename))
			{
				return false;
			}
			$file_contents = $this->getTemplateFromCache($templatename);
			$this->_file = $templatename;
		}		

		if (!is_object($this->_compile_obj)) {
			require_once("./includes/SmartyLight/class.compiler.php");
			$this->_compile_obj = new compiler;
		}
		$this->_compile_obj->left_tag = $this->left_tag;
		$this->_compile_obj->right_tag = $this->right_tag;
		$this->_compile_obj->plugin_dir = &$this->plugin_dir;
		$this->_compile_obj->template_dir = &$this->template_dir;
		$this->_compile_obj->cache = $this->cache;
		$this->_compile_obj->_compile_id = $this->_compile_id;
		$this->_compile_obj->_vars = &$this->_vars;
		$this->_compile_obj->_confs = &$this->_confs;
		$this->_compile_obj->_plugins = &$this->_plugins;
		$this->_compile_obj->_linenum = &$this->_linenum;
		$this->_compile_obj->_file = &$this->_file;
		$output = $this->_compile_obj->_compile_file($file_contents);
		
		// Dont write if output is empty
		if (trim($output) == "")
		{
			return false;
		}

		$f = fopen("./cache/".$name, "w+");
		fwrite($f, $output);
		fclose($f);
		@chmod("./cache/".$name, 0666);

		ob_start();
		if ($silent)
		{
			$evalreturn = @eval(' ?>' . $output . '<?php return true;');			
		} else {
			$evalreturn = eval(' ?>' . $output . '<?php return true;');			
		}
		$output = ob_get_contents();
		ob_end_clean();

		// return false if we got a parse error here
		if ($evalreturn == false)
		{
			return false;
		}

		return $output;
	}

	/*
	* Displays raw template
	*/
	function displayRawTemplate($templatename)
	{
		global $_SWIFT;

		$start = fetchmicrotime();
		// We salt the template name with type and group as user is in client area
		$name = md5($templatetype. ":". $this->groupid .":".$templatename).'.php';
		$this->fetchTemplate($templatename);

		if (!$this->cacheTemplate($templatename))
		{
			return false;
		}
		$file_contents = $this->getTemplateFromCache($templatename);
		$this->_file = $templatename;

		if (!is_object($this->_compile_obj)) {
			require_once("./includes/SmartyLight/class.compiler.php");
			$this->_compile_obj = new compiler;
		}
		$this->_compile_obj->left_tag = $this->left_tag;
		$this->_compile_obj->right_tag = $this->right_tag;
		$this->_compile_obj->plugin_dir = &$this->plugin_dir;
		$this->_compile_obj->template_dir = &$this->template_dir;
		$this->_compile_obj->cache = $this->cache;
		$this->_compile_obj->_compile_id = $this->_compile_id;
		$this->_compile_obj->_vars = &$this->_vars;
		$this->_compile_obj->_confs = &$this->_confs;
		$this->_compile_obj->_plugins = &$this->_plugins;
		$this->_compile_obj->_linenum = &$this->_linenum;
		$this->_compile_obj->_file = &$this->_file;
		$output = $this->_compile_obj->_compile_file(preg_replace('#<{\$(.*)}>#sU', '&lt;{$\1}&gt;', $file_contents));
		
		$result = array();
		// Dont write if output is empty
		if (trim($output) == "")
		{
			$result["compiletime"] = 0;
			$result["status"] = false;
			return $result;
		}

		ob_start();
		if ($silent)
		{
			$evalreturn = @eval(' ?>' . $output . '<?php return true;');
		} else {
			$evalreturn = eval(' ?>' . $output . '<?php return true;');
		}
		$output = ob_get_contents();
		ob_end_clean();

		$end = fetchmicrotime();

		// return false if we got a parse error here
		if ($evalreturn == false)
		{
			$result["compiletime"] = $end-$start;
			$result["status"] = false;
			return $result;
		}

		$result["compiletime"] = $end-$start;
		$result["status"] = $output;
		return $result;
	}
}
?>